import { RandUtil } from "../../util/RandUtil";
import BaseAI, { IBaseAI } from "./BaseAI";
import SnakeNode from "../SnakeNode";

const ru = RandUtil

export interface IAIFindSnake extends IBaseAI {
    findDis: number | [number, number]
    stopDis: number | [number, number]
}

export default class AIFindSnake extends BaseAI {

    private _findDisArr: number[]
    private _stopDisArr: number[]
    private _findDis: number
    private _stopDis: number

    constructor(obj: IAIFindSnake) {
        super(obj)
        this._findDisArr = this.toMinMax(obj.findDis)
        this._stopDisArr = this.toMinMax(obj.stopDis)
    }

    getKey(): string { return "ai_find_snake" }

    aiStart() {
        let head = this.head
        this._findDis = ru.rand2(this._findDisArr) * head.w + head.w
        this._stopDis = ru.rand2(this._stopDisArr) * head.w + head.w
        let findCol = head.cp().setW(this._findDis)
        let chunks = this.world.getChunks(findCol)
        let heads = this.world.getSnakeHeads(chunks)

        if (!heads.some(head => {
            if (head.owner != this.snake) {
                return findCol.collide(head)
            }
        })) {
            this.recheck()
        }
    }

    ai(dt: number): void {

        if (this.aiVal.nearestNode && this.aiVal.nearestNode.dis(this.head) >= this._stopDis) {
            this.recheck()
            return
        }

        let myHead = this.head
        let findHead: SnakeNode
        let minDis: number = Number.MAX_SAFE_INTEGER
        let findCol = myHead.cp().setW(this._findDis)
        let chunks = this.world.getChunks(findCol)
        let heads = this.world.getSnakeHeads(chunks)

        heads.forEach(head => {
            //找到检测范围内的最近的蛇头部节点
            if (head.owner != this.snake && findCol.collide(head)) {
                let dis = findCol.dis(head)
                if (dis < minDis) {
                    minDis = dis
                    findHead = head
                }
            }
        })

        if (findHead && minDis >= this._stopDis) {
            myHead.toAng = myHead.angTo(findHead)
        } else {
            this.recheck()
        }
    }

    aiStop() {
    }

}